package com.study.netProtocol.tcp;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author ysy
 * @version 1.0
 * @Title: TcpServerHandler
 * @Note <b>ProjectName:</b> Pre-research
 * <br><b>PackageName:</b> com.study.netProtocol.tcp
 * <br><b>ClassName:</b>
 * <br><b>Date:</b>

 */
public class TcpServerHandler extends Thread{

    private Socket sock;

    public TcpServerHandler(Socket sock) {
        this.sock = sock;
    }

    @Override
    public void run() {
        OutputStream output = null;
        InputStream input = null;
        StringBuilder clientAddress = new StringBuilder();
        try {
            output = this.sock.getOutputStream();
            input = this.sock.getInputStream();
            handle(input, output);
            clientAddress.append(this.sock.getInetAddress().getHostAddress());
            clientAddress.append(this.sock.getPort());
            this.sock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("client "+clientAddress.toString()+" disconnected.");
    }

    private void handle(InputStream input, OutputStream output) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
        writer.write("hello\n");
        writer.flush();
        for (;;) {
            String s = reader.readLine();
            if (s.equals("bye")) {
                writer.write("bye\n");
                writer.flush();
                break;
            }
            System.out.println("接收到数据：" + s);
            writer.write("ok: " + s + "\n");
            // 强制发送缓冲区数据
            writer.flush();
        }
    }

}
